import axios from 'axios'
import { Message } from 'element-ui'
import store from '../store'
import router from '../router'

const service = axios.create({
    baseURL: 'http://localhost:8080',//process.env.baseURL,
    timeout: 5000,
    responseType: 'json',
    withCredentials: true,
    // headers: {
    //     'Content-Type': 'appliction/json;charset=utf-8'
    // }
})

service.interceptors.request.use(
    config => {
        if (!store.getters.currentUser && config.url != '/user/login') {
            router.replace({
                path: 'login',
                query: {
                    redirect: router.currentRoute.fullPath
                }
            })
        }
        return config;
    },
    error => {
        Message({
            showClose: true,
            message: error,
            type: 'warning'
        });
        return Promise.reject(error);
    }
)

service.interceptors.response.use(
    response => {
        if (response.status === 200) {
            if (response.data) {
                switch (response.data.code) {
                    case -2:
                        router.replace({
                            path: 'login',
                            query: {
                                redirect: router.currentRoute.fullPath
                            }
                        })
                        break;
                }
            }
            return Promise.resolve(response);
        } else {
            return Promise.reject(response);
        }
    },
    error => {
        // if (error.response.data.code) {
        //     switch (error.response.data.code) {
        //         case -2:
        //             router.replace({
        //                 path: 'login',
        //                 query: {
        //                     redirect: router.currentRoute.fullPath
        //                 }
        //             })
        //             break;
        //         default:
        //             Message({
        //                 message: error.response.data.message,
        //                 duration: 1500,
        //                 forbidClick: true
        //             });
        //     }
        //     return Promise.reject(error.response);
        // }
        console.log(error)
    }
)

export default service;